package cn.lngaosu.lwyd.module.integration.service.weibouserscounts;

import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.lngaosu.lwyd.framework.common.util.http.HttpUtils;
import cn.lngaosu.lwyd.module.infra.service.config.ConfigService;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weixinvideoliverecord.WeixinvideoLiverecordDO;
import cn.lngaosu.lwyd.module.integration.service.apptoken.AppTokenService;
import cn.lngaosu.lwyd.module.integration.service.weixinvideoliverecord.WeixinvideoLiverecordServiceImpl;
import cn.lngaosu.lwyd.module.system.dal.dataobject.webinterfacelog.WebinterfaceLogDO;
import cn.lngaosu.lwyd.module.system.dal.mysql.webinterfacelog.WebinterfaceLogMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import cn.lngaosu.lwyd.module.integration.controller.admin.weibouserscounts.vo.*;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weibouserscounts.WeiboUserscountsDO;
import cn.lngaosu.lwyd.framework.common.pojo.PageResult;
import cn.lngaosu.lwyd.framework.common.pojo.PageParam;
import cn.lngaosu.lwyd.framework.common.util.object.BeanUtils;

import cn.lngaosu.lwyd.module.integration.dal.mysql.weibouserscounts.WeiboUserscountsMapper;

import static cn.lngaosu.lwyd.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.convertList;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.diffList;
import static cn.lngaosu.lwyd.module.integration.enums.ErrorCodeConstants.*;

/**
 * 微博用户基本信息 Service 实现类
 *
 * @author 张恒
 */
@Service
@Validated
public class WeiboUserscountsServiceImpl implements WeiboUserscountsService {
    private static final Logger logger = LoggerFactory.getLogger(WeiboUserscountsServiceImpl.class);

    @Resource
    private WeiboUserscountsMapper weiboUserscountsMapper;
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private ConfigService configService;
    @Resource
    private WebinterfaceLogMapper webinterfaceLogMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Long createWeiboUserscounts(WeiboUserscountsSaveReqVO createReqVO) {
        // 插入
        WeiboUserscountsDO weiboUserscounts = BeanUtils.toBean(createReqVO, WeiboUserscountsDO.class);
        weiboUserscountsMapper.insert(weiboUserscounts);
        // 返回
        return weiboUserscounts.getId();
    }

    @Override
    public void updateWeiboUserscounts(WeiboUserscountsSaveReqVO updateReqVO) {
        // 校验存在
        validateWeiboUserscountsExists(updateReqVO.getId());
        // 更新
        WeiboUserscountsDO updateObj = BeanUtils.toBean(updateReqVO, WeiboUserscountsDO.class);
        weiboUserscountsMapper.updateById(updateObj);
    }

    @Override
    public void deleteWeiboUserscounts(Long id) {
        // 校验存在
        validateWeiboUserscountsExists(id);
        // 删除
        weiboUserscountsMapper.deleteById(id);
    }

    @Override
        public void deleteWeiboUserscountsListByIds(List<Long> ids) {
        // 校验存在
        validateWeiboUserscountsExists(ids);
        // 删除
        weiboUserscountsMapper.deleteByIds(ids);
        }

    private void validateWeiboUserscountsExists(List<Long> ids) {
        List<WeiboUserscountsDO> list = weiboUserscountsMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(WEIBO_USERSCOUNTS_NOT_EXISTS);
        }
    }

    private void validateWeiboUserscountsExists(Long id) {
        if (weiboUserscountsMapper.selectById(id) == null) {
            throw exception(WEIBO_USERSCOUNTS_NOT_EXISTS);
        }
    }

    @Override
    public WeiboUserscountsDO getWeiboUserscounts(Long id) {
        return weiboUserscountsMapper.selectById(id);
    }

    @Override
    public PageResult<WeiboUserscountsDO> getWeiboUserscountsPage(WeiboUserscountsPageReqVO pageReqVO) {
        return weiboUserscountsMapper.selectPage(pageReqVO);
    }

    @Override
    public void syncWeiboUserscounts() {
        // 获取token
        String weiboToken = appTokenService.getWeiboToken();
        if (StringUtils.isEmpty(weiboToken)) {
            throw exception(WEIBO_TOKEN_NOT_EXISTS);
        }

        // 接口配置
        String configValue = configService.getConfigValueByKey("weiboConfig");
        if (StringUtils.isEmpty(configValue)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        JSONObject configJo = JSONObject.parseObject(configValue);
        // 接口开关
        String onOff = configJo.getString("onOff");
        if (!"on".equals(onOff)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        // 获取地址
        String weiboUids = stringRedisTemplate.opsForValue().get("weiboUid");
        String usersCountsUrl = configJo.getString("usersCountsUrl");
        usersCountsUrl = usersCountsUrl + "?access_token=" + weiboToken + "&uids=" + weiboUids;

        // 构造请求参数
        JSONObject params = new JSONObject();

        // 初始化日志数据（默认成功）
        WebinterfaceLogDO webinterfaceLogDO = new WebinterfaceLogDO();
        webinterfaceLogDO.setInterfaceSystemName("微博");
        webinterfaceLogDO.setInterfaceName("获取用户基本信息");
        webinterfaceLogDO.setInterfaceUrl(usersCountsUrl);
        webinterfaceLogDO.setInterfaceRequestMethod("GET");
        webinterfaceLogDO.setInterfaceParam(null);
        webinterfaceLogDO.setInterfaceStatus("成功");
        webinterfaceLogMapper.insert(webinterfaceLogDO);

        try {
            String result = HttpUtils.get(usersCountsUrl, new HashMap<>());

            // 解析接口结果
            Object resultObj = JSON.parse(result);
            if (resultObj instanceof JSONObject) {
                JSONObject resultJo = JSONObject.parseObject(result);
                Integer errcode = resultJo.getInteger("error_code");
                if (ObjectUtils.isNotEmpty(errcode)) {
                    webinterfaceLogDO.setInterfaceStatus("失败");
                    webinterfaceLogDO.setInterfaceErrorInfo(result);
                    webinterfaceLogMapper.updateById(webinterfaceLogDO);
                    return;
                }
            } else if (resultObj instanceof JSONArray) {
                JSONArray resultJa = JSONArray.parseArray(result);
                for (int i = 0; i < resultJa.size(); i++) {
                    JSONObject jsonObject = resultJa.getJSONObject(i);
                    Long weiboUid = jsonObject.getLong("id");
                    LocalDate localDate = LocalDate.now();
                    WeiboUserscountsDO weiboUserscountsDO = BeanUtils.toBeanIgnoreProperties(jsonObject, WeiboUserscountsDO.class, CopyOptions.create().setIgnoreProperties("id"));
                    weiboUserscountsDO.setWeiboUid(weiboUid);
                    weiboUserscountsDO.setSyncDate(localDate);

                    // 判断数据是更新还是插入
                    LambdaQueryWrapper<WeiboUserscountsDO> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WeiboUserscountsDO::getWeiboUid, weiboUid)
                            .eq(WeiboUserscountsDO::getSyncDate, localDate);
                    List<WeiboUserscountsDO> weiboUserscountsDOS = weiboUserscountsMapper.selectList(queryWrapper);
                    if (CollectionUtils.isNotEmpty(weiboUserscountsDOS)) {
                        weiboUserscountsDO.setId(weiboUserscountsDOS.get(0).getId());
                    }

                    weiboUserscountsMapper.insertOrUpdate(weiboUserscountsDO);
                }
            }

            webinterfaceLogDO.setInterfaceErrorInfo(result);
            webinterfaceLogMapper.updateById(webinterfaceLogDO);

        } catch (Exception e) {
            webinterfaceLogDO.setInterfaceStatus("失败");
            webinterfaceLogDO.setInterfaceErrorInfo(e.getMessage());
            webinterfaceLogMapper.updateById(webinterfaceLogDO);
            logger.error("微博【获取用户基本信息】接口调用失败！", e);
        }
    }

}